package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public void register(String username, String password) {
        //加密
        String md5String = Md5Util.getMD5String(password);
        //添加
        userMapper.add(username, md5String);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl, id);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd), id);
    }
    @Override
    public PageBean<User> findUsersByPage(int pageNum, int pageSize) {
        // 计算数据库查询的起始位置
        int start = (pageNum - 1) * pageSize;

        // 查询总记录数
        long total = userMapper.countUsers();

        // 查询当前页的数据
        List<User> users = userMapper.findUsersByPage(start, pageSize);

        // 封装分页结果
        PageBean<User> pageBean = new PageBean<>();
        pageBean.setTotal(total);
        pageBean.setItems(users);
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);

        return pageBean;
    }
    @Override
    public void deleteUser(Long userId) {
        userMapper.deleteUser(userId);
    }


}